import { useRef } from "react";
import styles from "./index.module.less";
import {
	ProForm,
	ProFormInstance,
	ProFormSelect,
	ProFormText,
	ProFormDateRangePicker,
	ProFormRadio
} from "@ant-design/pro-components";
import { Affix, Button, Col, ConfigProvider, Flex, Row, Space, message, Input, Form } from "antd";
import { map } from "lodash";
import useUrl from "@/hooks/useUrl";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import { emojiRegex, newlineRegex } from "@/pages/product/Create";
import { createDiscount } from "@/api/modules/discount";
import dayjs from "dayjs";
import { SECOND_TAB_VALUES, USE_RANGE_TABS } from "../List/constant";

export default () => {
	const formRef = useRef<ProFormInstance>();
	const { navigate } = useUrl();

	const handleValuesChange = (changeValue: any) => {
		if (Object.hasOwn(changeValue, "course_name") && typeof changeValue.course_name === "string") {
			const newName = changeValue.course_name.replace(emojiRegex, "").replace(newlineRegex, "");
			formRef.current?.setFieldValue("course_name", newName);
		}
	};

	const handleSubmit = () => {
		const values = formRef.current?.getFieldsFormatValue?.();
		const [startDate, endDate] = values.dateRange ?? []; // 获取日期范围
		// 转换为时间戳
		const startTime = dayjs(startDate).valueOf();
		const endTime = dayjs(endDate).valueOf();
		const requestData = {
			...values,
			start_time: startDate,
			end_time: endDate,
			dataRange: null,
			discount_val: values?.discount_val / 100 || 1
		};
		delete requestData.dataRange;
		const callback = () => {
			createDiscount(requestData).then((res: any) => {
				if (res?.code === RESULT_CODES.SUCCESS) {
					message.success("创建成功");
					handleBack();
				}
			});
		};
		formRef.current?.validateFieldsReturnFormatValue?.().then(() => {
			callback();
		});
	};

	const handleBack = () => {
		navigate("/discount");
	};

	const DISCOUNT_TYPES = [
		{
			label: "满减券",
			value: SECOND_TAB_VALUES.fullCut,
			disabled: true
		},
		{
			label: "折扣券",
			value: SECOND_TAB_VALUES.percentCut
		}
	];

	return (
		<ConfigProvider
			theme={{
				components: {
					Radio: {
						wrapperMarginInlineEnd: 60
					},
					Checkbox: {
						marginXS: 60,
						borderRadiusSM: 50
					}
				}
			}}
		>
			<Loading isHeight100 loading={false}>
				<div className={styles.container}>
					<ProForm
						colon={false}
						submitter={false}
						formRef={formRef}
						layout="horizontal"
						onValuesChange={handleValuesChange}
						labelCol={{ span: 4 }}
					>
						<div className={styles.content_wrap}>
							<div className={styles.content}>
								<div style={{ height: "32px", marginBottom: "12px" }}>
									<div className={styles.title}>创建优惠券</div>
								</div>
								<ProFormText
									label="优惠券名称"
									name="name"
									rules={[{ required: true, message: "请输入优惠券名称" }]}
									placeholder={"请输入优惠券名称"}
								/>
								<ProFormRadio.Group
									name="type"
									label="优惠券类型"
									initialValue={SECOND_TAB_VALUES.percentCut}
									options={DISCOUNT_TYPES}
									rules={[{ required: true, message: "请选择优惠券类型" }]}
								/>
								<ProFormDateRangePicker
									name="dateRange"
									label="有效期"
									required
									rules={[{ required: true, message: "请选择" }]}
									fieldProps={{
										showTime: {
											format: "HH:mm:ss", // 时间格式
											defaultValue: [
												dayjs("08:00:00", "HH:mm:ss"),
												dayjs("18:00:00", "HH:mm:ss") // 结束时间的默认值
											]
										},
										format: "YYYY-MM-DD HH:mm:ss", // 日期时间格式
										placeholder: ["开始时间", "结束时间"], // 占位符
										style: { width: "582px" }
									}}
								/>
								<ProForm.Item noStyle shouldUpdate>
									{form => {
										const selectValue = form.getFieldValue("type");
										return selectValue === "fixed_amount" ? (
											<Form.Item label="面额门槛" required>
												<Space.Compact>
													<Form.Item name="min_order_amount" noStyle rules={[{ required: true, message: "请输入满减金额" }]}>
														<Input addonBefore="满" placeholder="请输入" style={{ width: "50%" }} />
													</Form.Item>
													<Form.Item name="discount_amount" noStyle rules={[{ required: true, message: "请输入满减金额" }]}>
														<Input addonBefore="减" placeholder="请输入" style={{ width: "50%" }} />
													</Form.Item>
												</Space.Compact>
											</Form.Item>
										) : (
											<ProFormText
												label="折扣率"
												name="discount_val"
												rules={[
													{ required: true, message: "请输入折扣率" },
													{
														pattern: /^(0?\.\d+|[1-9]\d?(\.\d+)?)$/, // 匹配大于 0 且小于 100 的数字
														message: "请输入大于 0 且小于 100 的数字"
													}
												]}
												placeholder={"请输入小于100并大于0的数字"}
												fieldProps={{
													type: "number",
													min: 0, // 最小值
													max: 100, // 最大值
													addonAfter: "折"
												}}
											/>
										);
									}}
								</ProForm.Item>
								<ProFormText
									label="每人限用"
									name="single_use_per_user"
									rules={[{ required: true, message: "请输入限用次数" }]}
									placeholder={"请输入限用次数"}
									fieldProps={{
										addonAfter: "次"
									}}
								/>
								<ProFormSelect
									label="使用范围"
									name={"category_pid"}
									placeholder={"请选择使用范围"}
									rules={[{ required: true, message: "请选择" }]}
									request={async () => {
										return map(USE_RANGE_TABS, (item: any) => ({
											label: item.label,
											value: item.key
										}));
									}}
									className={styles.customInputWidth}
								/>
								<ProFormText
									label="可使用次数"
									name="max_uses"
									rules={[{ required: true, message: "请输入" }]}
									placeholder={"请输入优惠券可使用次数"}
									fieldProps={{
										addonAfter: "次"
									}}
								/>
							</div>
						</div>
					</ProForm>
					<Affix offsetBottom={0}>
						<Flex justify="center" className={styles.btns}>
							<Space size={10}>
								<Button ghost type="primary" onClick={() => navigate(-1)}>
									返回
								</Button>
								<Button type="primary" onClick={handleSubmit}>
									创建
								</Button>
							</Space>
						</Flex>
					</Affix>
				</div>
			</Loading>
		</ConfigProvider>
	);
};
